import {addToCart,getCartList,checkState,deleteCart} from 'http'
const OK =200
export default {
    state:{
        cartList:[]
    },
    getters:{
        //全选状态,依赖每个商品的isChecked
        cart_checkAll(state){
            let flag = 0
            state.cartList.forEach(goods=>{
                if(goods.isChecked === 1){
                    flag++
                }
            })
            //有商品才可以全选,当计算器和商品列表的长度一样,则全选
            return state.cartList.length >=1 && flag === state.cartList.length 
        },
        //总价
        cart_totalPrice(state){
            let flag = 0
            state.cartList.forEach(goods=>{
                flag += (goods.cartPrice *goods.skuNum)
            })
            return flag
        },
        //已选中商品数量
        cart_checkedNum(state){
            let flag = 0
            state.cartList.forEach(item => {
                if(item.isChecked === 1){
                    flag += item.skuNum
                }
            })
            return flag
        }
    },
    mutations:{
        getCartList(state,cartList){
            state.cartList = cartList
        }
    },
    actions:{
        //添加购物车请求
        async addToCart(store,{skuId,skuNum}){
            try {
                const {code} = await addToCart(skuId,skuNum)
                return code
            } catch (error) {
                throw new Error(error)
            }
        },
        //获取购物车列表
        async getCartList ({commit}){
            const {code,data} = await getCartList()
            if(code === OK){
                // console.log(data)
                commit('getCartList',data)
            }
        },
        //切换商品选中状态
        async checkState(store,{skuID,isChecked}){
            const {code} = await checkState(skuID,isChecked)
            return code
        },
        //切换全选按钮的状态(依赖于单个商品的请求),只有当所有的商品的状态都请求回来后才能成功
        async checkAllState(store,val){
            let all = []
            store.state.cartList.forEach(item =>{
                if(item.isChecked !== val){
                    let p = store.dispatch('checkState', {skuID:item.skuId,isChecked:val})
                    // console.log(p)
                    all.push(p)
                }
            })
        //    console.log(Promise.all(all));
            return Promise.all(all)
        },
        //删除单个商品
        async deleteCart(store,skuId){
            try {
                const {code} = await deleteCart(skuId)
                return code
            } catch (error) {
                throw new Error(error)
            }
            
        },
        //删除全部选中(依赖于删除单个接口)
        async deleteAllCheckedCart(store){
            let all = []
            store.state.cartList.forEach(item=>{
                if(item.isChecked === 1){
                   const p =  store.dispatch('deleteCart',item.skuId)
                   all.push(p)
                }
            })
            return Promise.all(all)
        }
    }
}